
import * as path from 'path';
import * as fs from 'fs';
import { langConfig } from '.';

interface FNode {
  path: string,
  isFile: boolean;
  children: Array<FNode>
}

export class FilesModel {

  _files: any = {};
  _tree: FNode;

  constructor(dirPath: string) {
    this._tree = {
      path: dirPath,
      isFile: false,
      children: [],
    };

    this.getFileTree(this._tree);
    console.log(this._tree);
  }

  getFileTree(fnode: FNode) {
    if (fnode.isFile) { return; }
    const dirPath = fnode.path;
    var files = fs.readdirSync(dirPath);
    if (files.length === 0) { return; }
    fnode.children = files
      .filter(val => {
        if (langConfig.excludesPath().indexOf(val) > -1 || val.indexOf('.') === 0) { return false; }
        const filename = path.join(fnode.path, val);
        if (fs.statSync(filename).isDirectory()) { return true; }
        return fs.statSync(filename).isFile() && langConfig.matchFile().test(val);
      })
      .map(val => {
        const data: FNode = {
          path: path.join(fnode.path, val),
          isFile: fs.statSync(path.join(fnode.path, val)).isFile(),
          children: []
        };
        data.isFile && (this._files[data.path] = []);
        this.getFileTree(data);
        return data;
      });
  }

  get tree() {
    return this._tree;
  }


  get files() {
    return this._files;
  }
}